 import { EncodeRulesService } from './../../../../../@core/services/encoderRule/encode-rules.service';
import { Router } from '@angular/router';
import { PostEmploy } from './../../../../../@core/data/employ';
import { Component } from '@angular/core';
import { CascaderItem, DValidateRules, FileUploader, FormLayout, IFileOptions, IUploadOptions, DialogService } from 'ng-devui';
import { UserService } from 'src/app/@core/services/user/user.service';
import { RoleService } from 'src/app/@core/services/role/role.service';
import { environment } from 'src/environments/environment';
import { SelectWorkShopComponent } from 'src/app/@shared/components/select-work-shop/select-work-shop.component';
@Component({
  selector: 'app-add-employs',
  templateUrl: './add-employs.component.html',
  styleUrls: ['./add-employs.component.scss']
})
export class AddEmploysComponent {
  layoutDirection: FormLayout = FormLayout.Horizontal;
  isManagerType = ["是", "否"];
  isManager = "否";
  genderType = ["男", "女"];
  gender = "男";
  employTypes = ["本地员工", "外地员工"];
  employeeType = "本地员工";
  isDormitoryType = ["是", "否"];
  isInsuredType = ["参保", "未参保"];
  isInsured = "参保"
  isDormitory = "否";
  departmentOptions: any = [];//部门
  roleOptions: any = [];//角色
  isDropOver: boolean = false;
  EntryDate = new Date();
  uploadedFiles: Array<Object> = [];
  departmentId: Array<number> = [];
  UserRoles: any = [];
  UPLOADED: string = '上传成功';
  CANCELUPLOAD: string = '取消上传';
  fileUploaders: Array<FileUploader> = [];
  msgs: Array<Object> = [];//消息提示
  headerURL: String = '';
  uploadOptions: IUploadOptions = {
    uri: environment.apiUrl + '/User/UploadAvatar',
    maximumSize: 1024,
    checkSameName: true,
    fileFieldName: "file",
  };
  fileOptions: IFileOptions = {
    accept: '.png,.jpg,.jpeg,.gif,.bmp,.wbmp,.webp',
    multiple: false
  };
  PostEmploy: PostEmploy = {
    employeeCode: '',
    name: '',
    jobNumber: '',
    departmentId: null,
    isManager: false,
    accountNumber: '',
    password: '',
    position: null,
    workshop: null,
    gender: false,
    entryDate: null,
    ownerPhoneNumber: null,
    ownerEmail: null,
    identityCardNumber: null,
    bankName: null,
    accountHolder: null,
    bankAccountNumber: null,
    address: null,
    employeeType: false,
    isInsured: null,
    contractStartDate: null,
    contractEndDate: null,
    resignationDate: null,
    salaryCategory: null,
    isDormitory: false,
    headImgUrl: null,
    enabled: true,
    userRoles: [],
    departmentName: '',
    departmentNum: ''
  }
  PostEmployRules: { [key: string]: DValidateRules } = {
    employeeCodeRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message:
            '不能包含空格'
          ,
        },
      ],
    },
    nameRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
      ],
    },
    jobNumberRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message:
            '不能包含空格'
          ,
        },
      ],
    },
    accountNumberRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message:
            '不能包含空格'
          ,
        },
      ],
    },
    passwordules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 6 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message:
            '不能包含空格'
          ,
        },
      ],
    },
    UserRolesRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message:
            '不能包含空格'
          ,
        },
      ],
    },
    departmentIdules: {
      messageShowType: 'text',
      validators: [
        { required: true },
      ],
    },
    telephoneRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1, message: '请输入正确的手机号码' },
        { maxlength: 20, message: '请输入正确的手机号码' },
        { whitespace: true, message: '请输入正确的手机号码' },
      ],
    },
    emailRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 40 },
        { whitespace: true },
        {
          pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
          message: '请输入正确的邮箱，例如:example@example.com',
        }
      ],
    },
    cardNumberRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 18 },
        { whitespace: true },
        {
          pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message:
            '请输入正确的身份证号码'
          ,
        },
      ],
    },
    bankAccountNumberRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 19 },
        { whitespace: true },
        {
          pattern: /^\d+$/,
          message:
            '请输入正确的银行账号'
          ,
        },
      ],
    },
  }
  dispaly: boolean = false;
  constructor(private UserService: UserService, private roleService: RoleService, private Router: Router, private EncodeRulesService: EncodeRulesService, private dialogService: DialogService) { }
  ngOnInit(): void {
    this.PostEmploy.isManager = this.isManager == '是' ? true : false
    this.PostEmploy.gender = this.gender == '男' ? true : false
    this.PostEmploy.employeeType = this.employeeType == '本地员工' ? true : false
    this.PostEmploy.isDormitory = this.isDormitory == '是' ? true : false
    this.UserService.GetAllDepartments(1, 999).subscribe(
      (data: any) => {
        const department = data.items.map(item => {
          if (!item.enable) {
            item.disabled = true;
          }
          return item;
        });
        this.departmentOptions = this.convertToCascaderItem(department, 'departmentId')
      }
    )
    this.roleService.getAllRoles(1, 999).subscribe(
      (data: any) => {
        this.roleOptions = data.items
  .filter((item: { name: any; }) => item.name !== '超级管理员')
  .map((item: { name: any; }) => item.name);
      }
    )
    this.EncodeRulesService.GenerateWarehouseCodeRule('员工编码','员工编码').subscribe((data: any) => {
      this.PostEmploy.employeeCode = data
    })
  }
  dropdownToggle($event: any) {
  }//下拉菜单
  convertToCascaderItem(data: any[], valueKey: any): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.name,
        value: item[valueKey],
        icon: item.icon,
        name: item.departmentCode,
        disabled: item.disabled,
      };
      if (item.subDepartments) {
        cascaderItem.children = this.convertToCascaderItem(item.subDepartments, valueKey);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  submit({ valid, directive }) {
    this.dispaly = true
    if (this.departmentId.length > 0) {
      this.PostEmploy.departmentId = this.departmentId[this.departmentId.length - 1]
    }
    this.PostEmploy.isManager = this.isManager == '是' ? true : false
    this.PostEmploy.gender = this.gender == '男' ? true : false
    this.PostEmploy.employeeType = this.employeeType == '本地员工' ? true : false
    this.PostEmploy.isDormitory = this.isDormitory == '是' ? true : false
    this.PostEmploy.isInsured = this.isInsured == '参保' ? true : false
    this.PostEmploy.entryDate = this.EntryDate.toISOString().slice(0, 10)
    let postEmployNonNull = Object.entries(this.PostEmploy).reduce((newObj, [key, value]) => {
      if (value !== null) {
        newObj[key] = value;
      }
      return newObj;
    }, {});
    if (valid) {
      this.UserService.CreateEmploy(postEmployNonNull).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '人员添加成功！')
          setTimeout(() => {
            this.Router.navigate(['/pages/basicdata/employs']);
          }, 1000);
        },
        (error) => {
          if(error.status==404){
            this.showToast('error', '失败', '服务器连接失败');
          }else{
            this.showToast('error', '失败', error.error);
          }
        }
      )
    } else {
      this.showToast('warn', '警告', '请按照要求填写表单！')
    }
  }//提交
  onSuccess(event: any) {
    let response = JSON.parse(event[0].response);
    let avatarUrl = response.avatarUrl;
    this.PostEmploy.headImgUrl = avatarUrl.replace(environment.modifiedApiUrl, "");
    this.headerURL = avatarUrl;
  }//上传成功
  onError(event: any) {
  }//上传失败
  fileDrop(files: File) {
    this.isDropOver = false;
  }//拖拽文件
  fileOver(event: any) {
    this.isDropOver = event;
  }//拖拽文件
  fileSelect(files: any) {
  }//文件选择
  deleteFile(currFile: FileUploader) {
    this.fileUploaders = this.fileUploaders.filter((fileUploader) => {
      return currFile !== fileUploader;
    });
  }//删除文件
  cancel() {
    this.Router.navigate(['/pages/basicdata/employs'])
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  selectWorkShop(DialogService?: string) {
    let data = {
      display: false,
      placeholder: '请选择车间'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '800px',
      title: '车间',
      data: data,
      content: SelectWorkShopComponent,
      dialogtype: DialogService,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              this.PostEmploy.workshop = results.modalContentInstance.selectData.workshopName
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  findDepartmentById(departments: any[], departmentId: number): any {
    for (const dept of departments) {
      if (dept.value === departmentId) {
        return dept;
      }
      if (dept.children && dept.children.length > 0) {
        const found = this.findDepartmentById(dept.children, departmentId);
        if (found) {
          return found;
        }
      }
    }
    return null;
  }
  cascaderonChanges($event: any) {
    this.dispaly = true;
    const selectedDepartmentId = $event[$event.length - 1]
    const selectedDepartment = this.findDepartmentById(this.departmentOptions, selectedDepartmentId);
    console.log(selectedDepartment);
    if (selectedDepartment) {
      this.PostEmploy.departmentName = selectedDepartment.label;
      this.PostEmploy.departmentNum = selectedDepartment.name;
    } else {
      // 处理未找到相应部门的情况
      console.error('未找到相应的部门信息');
    }
  }
}
